<?php

declare(strict_types=1);
/**
 * This file is part of MineAdmin.
 *
 * @link     https://www.mineadmin.com
 * @document https://doc.mineadmin.com
 * @contact  root@imoi.cn
 * @license  https://github.com/mineadmin/MineAdmin/blob/master/LICENSE
 */

namespace App\Http\Api\Controller\V1;

use App\Http\Api\Middleware\TokenMiddleware;
use App\Http\Common\Controller\AbstractController;
use App\Http\Common\Result;
use App\Http\CurrentUser;
use App\Model\Course;
use Hyperf\Swagger\Annotation\HyperfServer;
use Hyperf\Swagger\Annotation\Post;
use App\Service\Course\CourseService;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\Swagger\Annotation\Get;

#[HyperfServer(name: 'http')]
final class CourseController extends AbstractController
{
    public function __construct(
        private readonly CourseService $service,
        private readonly CurrentUser $user,
    ) {}

    #[Get(
        path: '/api/v1/course/{id:\d+}/task/{task_id:\d+}',
        operationId: 'ApiV1CourseDetail',
        summary: '课时详情',
        tags: ['api'],
    )]
    public function taskinfo($id, $task_id): Result
    {
        $course = $this->service->findById($id);
        if (!$course) {
            return $this->error(
                '不存在的课程'
            );
        }

        /**
         * @var Course $course
         */
        $course->load([

            'tasks' => function ($q) {
                $q->with([
                    'lives',
                    'homeworks',
                    'taskable'
                ])->select(
                    'id',
                    'course_id',
                    'section_id',
                    'taskable_type',
                    'taskable_id',
                    'data',
                    'video'
                )->whereTaskableType('task_micro_course');
            }
        ]);
        $currect_task = $course->tasks->first(fn($item) => $item->id == $task_id);
        return $this->success([
            'course' => [
                'courseName' => $course->title,
                'selectCourseId' => $task_id,
                'selectName' => $currect_task?->taskable->title,
                'selectVideo' => $currect_task?->taskable->src,
                'tabs' => [
                    [
                        'lessons' => $course->tasks->map(fn($task) => [
                            'id' => $task->id,
                            'name' => $task->taskable->title,
                            'time' => sprintf(
                                '%s::%s::%s',
                                $task->taskable->duration['h'] ?? '00',
                                $task->taskable->duration['m'] ?? '00',
                                $task->taskable->duration['s'] ?? '00',
                            )
                        ])
                    ],
                    [
                        'information' => $currect_task->data
                    ],
                    [
                        'work' => $currect_task->homeworks->map(fn($item) => $item->only(['id', 'title']))
                    ],
                    [
                        'video' => $currect_task->video
                    ],
                    [
                        'live' => $currect_task->lives->map(fn($item) => [
                            'thumb' => $item->thumb,
                            'name' => $item->title,
                            'id' => $id
                        ])
                    ],
                ],
            ],
        ]);
    }
    #[Get(
        path: '/api/v1/course/{id:\d+}',
        operationId: 'ApiV1CourseDetail',
        summary: '课程详情',
        tags: ['api'],
    )]
    public function courseinfo($id): Result
    {
        $course = $this->service->findById($id);
        if (!$course) {
            return $this->error(
                '不存在的课程'
            );
        }

        /**
         * @var Course $course
         */
        $course->load([
            'teacher' => fn($q) => $q->select('id', 'nickname', 'avatar', 'signed'),
            // 'tags',
            // 'categorys',
            // 'sections' => function ($q) {
            //     $q->whereParentId(0)->with(
            //         ['children.tasks.taskable']
            //     );
            // },
            'tasks' => function ($q) {
                $q->with([
                    // 'lives',
                    // 'homeworks',
                    'taskable'
                ])->select(
                    'id',
                    'course_id',
                    'section_id',
                    'taskable_type',
                    'taskable_id',
                    'data',
                    'video'
                )->whereTaskableType('task_micro_course');
            }
        ]);
        return $this->success([
            'course' => [
                'courseName' => $course->title,
                'courseDesc' => $course->description,
                'courseIntro' => $course->introduce,
                'teacherName' => $course->teacher->nickname,
                'teacherBio' => $course->teacher->signed,
                'productSelling' => $course->video_src,
                'lessons' => $course->tasks->map(fn($task) => [
                    'id' => $task->id,
                    'name' => $task->taskable->title,
                    'time' => sprintf(
                        '%s::%s::%s',
                        $task->taskable->duration['h'] ?? '00',
                        $task->taskable->duration['m'] ?? '00',
                        $task->taskable->duration['s'] ?? '00',
                    )
                ]),
                // 'sections' => $course->sections->map(function ($s) {
                //     return [
                //         'id' => $s->id,
                //         'name' => $s->name,
                //         'children' => $s->children->map(function ($c) {
                //             return [
                //                 'id' => $c->id,
                //                 'name' => $c->name,
                //                 'lessons' => $c->tasks->map(function ($task) {
                //                     return [
                //                         'id' => $task->id,
                //                         'name' => $task->taskable->title,
                //                         'time' => sprintf(
                //                             '%s::%s::%s',
                //                             $task->taskable->duration['h'] ?? '00',
                //                             $task->taskable->duration['m'] ?? '00',
                //                             $task->taskable->duration['s'] ?? '00',
                //                         )
                //                     ];
                //                 })
                //             ];
                //         })
                //     ];
                // })
            ],
        ]);
    }

    #[Post(
        path: '/api/v1/course/{course_id:\d+}/task/{task_id:\d+}/start',
        operationId: 'ApiV1CourseTaskStart',
        summary: '课时开始',
        tags: ['api'],
    )]
    #[Middleware(TokenMiddleware::class)]
    public function courstTaskStart($course_id, $task_id)
    {
        $user = $this->user->user();
        $user->load(['courseTaskProgress' => function ($q) use ($task_id) {
            $q->whereCourseTaskId($task_id)->limit(1);
        }]);
        if ($user->courseTaskProgress->isNotEmpty()) {
            return $this->error('该课时已开始');
        }
        $user->startCourseTaskOnTaskId($task_id);

        return $this->success();
    }

    #[Post(
        path: '/api/v1/course/{course_id:\d+}/task/{task_id:\d+}/end',
        operationId: 'ApiV1CourseTaskEnd',
        summary: '课时结束',
        tags: ['api'],
    )]
    #[Middleware(TokenMiddleware::class)]
    public function courstTaskEnd($course_id, $task_id)
    {
        $user = $this->user->user();
        $user->load(['courseTaskProgress' => function ($q) use ($task_id) {
            $q->whereCourseTaskId($task_id)->limit(1);
        }]);
        if ($user->courseTaskProgress->isEmpty()) {
            return $this->error('该课时未开始');
        }
        if ($user->courseTaskProgress->first()->status == 2) {
            return $this->error('该课时已结束');
        }

        $user->courseTaskProgress->first()->endCourseTaskOnTaskId();

        return $this->success();
    }
}
